package com.sufen.seckill.study.LeetCode;


import com.sufen.seckill.study.LeetCodeHelper.ListNode;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.val;

/**
 * @Author sufen
 * @Date 2021/11/12 16:45
 * @Version 1.0
 * 功能描述：
 */
public class t2_25_k个一组翻转链表 {

    public static class ListNode{
        int val;
        ListNode next=null;
        public ListNode(int val){
            this.val=val;
        }
    }

    public static void main(String[] args) {
        ListNode t1=new ListNode(1);
        ListNode t2=new ListNode(2);
        ListNode t3=new ListNode(3);
        ListNode t4=new ListNode(4);

        t1.next=t2;
        t2.next=t3;
        t3.next=t4;
        ListNode res=reverseKGroup(t1,2);
        while(res!=null){
            System.out.print(res.val+"-");
            res=res.next;
        }
    }
    public static ListNode reverseKGroup(ListNode head, int k){
        if(k==1){
            return head;
        }

        ListNode res=head;
        int kc=k;


        while(kc>1){
            res=res.next;
            kc--;
        }

        ListNode cur1=head;
        ListNode cur2=head;
        ListNode prev=null;
        while(cur2!=null){
            for(int i=1;i<k;i++){
                cur2=cur2.next;
                if(cur2==null){
                    return res;
                }
            }
            ListNode next=cur2.next;
            cur2.next=null;
            if(prev!=null){
                prev.next=null;
            }
            ListNode[] list=reverseList(cur1,cur2);
            cur1=list[0];
            cur2=list[1];

            cur2.next=next;

            if(prev!=null){
                prev.next=cur1;
            }

            prev=cur2;

            cur1=next;
            cur2=next;
        }

        return res;
    }
    public static ListNode[] reverseList(ListNode head,ListNode tail){
        ListNode cur1=head;
        ListNode cur2=tail;
        ListNode prev=null;

        while(cur1!=null){
            ListNode next=cur1.next;
            cur1.next=prev;
            prev=cur1;
            cur1=next;
        }

        return new ListNode[]{tail,head};
    }
}
